package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.NotificationContactItemAdaptor;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListsDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class NotificationContactActivity extends AppCompatActivity {
    public ParentBleTransfer mParentBleTransfer;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private App mApp;
    private KidInfoEntity mKidInfoEntity;
    private int mViewProcess = 0;
    private ListView mListView;
    NotificationContactItemAdaptor mAdaptor;
    List<ContactListsDto> mContactList;


    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;
    private static final String TAG = "TAG";

    // ページジャンプ
    public static boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;

    private final static int SUCCESS_CODE = 200;
    private final static int CONTACT_OPT_REQUEST_CODE = 1;
    // プログラムロック
    private String mSyncLock = "syncLock";
    private JSONObject mJsonObj;
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "NotificationContactActivity_onCreate");
        setContentView(R.layout.activity_notification_contact);

        getIntentFromOkaeriNotification();
        mApp = (App) getApplication();
        initReceiver();
        mListView = findViewById(R.id.contactList);
        initListener();
        try {
            initContactList();
        } catch (Exception e) {
            Log.e(TAG,e.getMessage());
        }

        // 検索中...
//        String pDlgMsg = "キッズケータイから情報を取得しています...";
//        mDealWithWaitingDlg = new DealWithWaitingDlg(NotificationContactActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, true);
//        mDealWithWaitingDlg.show();
//        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
//
//        new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
    }

    public void getIntentFromOkaeriNotification(){
        try {
            Intent intent = getIntent();
            String jsonObjStr = intent.getStringExtra("jsonObject");
            mJsonObj = new JSONObject(jsonObjStr);
        } catch (JSONException e) {
            Log.e(TAG,e.getMessage());
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PowerSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }

    }


    @Override
    protected void onStop() {
        Log.i(TAG, "NotificationContactActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "NotificationContactActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "NotificationContactActivity_onActivityResult");
        initReceiver();
        int SUCCESS_CODE_100 = 100;
        if (resultCode == SUCCESS_CODE_100) {
            switch (requestCode) {
                case CONTACT_OPT_REQUEST_CODE:
                    getPositionFromContactOpt(data);
                    break;
            }
        }
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        Log.i(TAG, "NotificationContactActivity_onBackPressed");
        backView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "NotificationContactActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }


    public void initListener() {
        Log.i(TAG, "NotificationContactActivity_initListener");
        ImageView imageView = findViewById(R.id.backView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backView();
            }
        });
    }

    public void backView() {
        List<ContactListsDto> contactList = new ArrayList<>();
//        for (ContactListsDto dto:mContactList) {
//            if(dto.getName().equals("設定なし")){
//                mContactList.remove(dto);
//            }
//        }
        Iterator<ContactListsDto> iterator = mContactList.iterator();
        while (iterator.hasNext()) {
            ContactListsDto contactListDto = iterator.next();
            if(contactListDto.getName().equals("設定なし")){
                iterator.remove();
            }
        }
        Intent intent = new Intent();
        intent.putExtra("contactList", mContactList.toString());
        setResult(SUCCESS_CODE, intent);//200代表成功
        mPageJumpFlag=true;
        finish();
    }

    public void getPositionFromContactOpt(Intent data) {
        Log.i(TAG, "NotificationContactActivity_getPositionFromContactOpt");
        ContactListDto contactListDto = (ContactListDto) data.getSerializableExtra(Constants.KEY_CONTACT_OPT);
        int position = data.getIntExtra("position", -1);
        mContactList.get(position).setName(contactListDto.getName());
        mContactList.get(position).setPhone(contactListDto.getPhone());
        mContactList.get(position).setId(contactListDto.getId());
        mAdaptor.notifyDataSetChanged();
    }
//    public void backView(){
//        Log.i(TAG,"NotificationContactActivity_backView");
//        ImageView imageView = findViewById(R.id.backView);
//        imageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.putExtra("contactList", mContactList.toString());
//                setResult(200,intent);//200代表成功
//                finish();
//            }
//        });
//    }

    public void initReceiver() {
        Log.i(TAG, "NotificationContactActivity_initReceiver");

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);

        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }


    public JSONObject getInitData() {
        Log.i(TAG, "NotificationContactActivity_getInitData");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_RETURN_SETTINGS);
            jsonObject.put("data", JSONObject.NULL);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObject;
    }

    public void initContactList() throws Exception {
        Log.i(TAG, "NotificationContactActivity_initContactList");

        //getUser
        TextView tv_user = findViewById(R.id.userName);
        tv_user.setText(mApp.findKidInfoBySelect().getKidName()+ "のキッズケータイ");

        mContactList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ContactListsDto dto = new ContactListsDto();
            dto.setIndex(i);
            dto.setName("設定なし");
            mContactList.add(dto);
        }

        if(null != mJsonObj){
            JSONArray array = mJsonObj.getJSONObject("data").getJSONArray("contactList");
            if (array.length() > 0) {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject data = (JSONObject) array.get(i);
                    int index = data.getInt("index");
                    mContactList.get(index).setIndex(index);
                    mContactList.get(index).setName(data.getString("name"));
                    mContactList.get(index).setPhone(data.getString("phone"));
                    mContactList.get(index).setId(data.getInt("id"));
                }
            }
        }

        mAdaptor = new NotificationContactItemAdaptor(NotificationContactActivity.this, R.layout.activity_notification_contact_item, mContactList,
                new NotificationContactItemAdaptor.OnClickItemListenter() {
                    @Override
                    public void chooseItemClick(int position) {
                    }
                });
        mListView.setAdapter(mAdaptor);
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                    }

                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        // TODO Mimamori
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();

                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(NotificationContactActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(NotificationContactActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(NotificationContactActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "NotificationContactActivity_BroadcastReceiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch (mViewProcess) {
                            case Constants.SEND_KID_ENTER:
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                if (!mScreenOperate) {
                                    new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                                } else {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
                                    mDealWithWaitingDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    NotificationContactActivity.this.finish();
                                }
                                break;
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);

                    if (RequestMethodConstants.METHOD_GET_RETURN_SETTINGS.equals(jsonObject.getString("method"))) {
//                        mDealWithWaitingDlg.dismiss();


                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (Constants.IS_USING_OK.equals(data.getString("state"))) {

                            //send enter
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            mDealWithWaitingDlg.dismiss();
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(NotificationContactActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    NotificationContactActivity.this.finish();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (Constants.ON_SYNC_RESULT.equals(jsonObject.getString("result"))) {
                            // ページジャンプ
                            mPageJumpFlag = true;
                            //c
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(NotificationContactActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent(NotificationContactActivity.this,SettingActivity.class);
                                startActivity(intent1);
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
//                e.printStackTrace();
            }
        }
    };

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(NotificationContactActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };

}
